package com.open.capacity.controller;

import com.open.capacity.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis 消息过期异步通知监听器
 */
@Component
public class RedisMessageListener extends KeyExpirationEventMessageListener {
    private static Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);
    private static final String KEY_PRE_USING = "ORDER_USING"; //缓存中正在使用中的订单前缀
    //缓存中正在使用中的订单前缀
    private static final String KEY_PRE_UNPAID = "ORDER_UNPAID"; //缓存中未支付的订单前缀
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OrderService orderService;

    public RedisMessageListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        logger.info("收到 redis 过期异步通知：{}", message.toString());

        String redisKey = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        logger.info("redisKey : {}", redisKey);
        //针对特定的key进行处理
        if (redisKey.startsWith(KEY_PRE_USING)) {
            try {           //TODO
                String[] split = redisKey.split(":");
                String orcode = split[1];
                orderService.orderTimeEnd(orcode);
            } catch (Exception exp) {
                logger.info("业务处理失败：" + exp.getMessage());
            }
        }
        //如果到期之后，然后没有支付，则将订单变为无效订单
        if (redisKey.startsWith(KEY_PRE_UNPAID)) {
            try {           //TODO
                String[] split = redisKey.split(":");
                String orcode = split[1];
                orderService.InvalidationOrder(orcode);
            } catch (Exception exp) {
                logger.info("业务处理失败：" + exp.getMessage());
            }
        }
    }
}